package com.audaque.springboot.foshanupload.web.redisdemo.service.impl;

import com.audaque.springboot.foshanupload.web.redisdemo.model.Ur;
import com.audaque.springboot.foshanupload.web.redisdemo.service.Lock4jService;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.lock.executor.RedissonLockExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class Lock4jServiceImpl implements Lock4jService {


    @Autowired
    private LockTemplate lockTemplate;



    //默认获取锁超时3秒，30秒锁过期
    @Lock4j
    public void simple() {
        //do something
    }

    //完全配置，支持spel
    @Lock4j(keys = {"#user.id", "#user.name"}, expire = 60000, acquireTimeout = 1000)
    public Ur customMethod(Ur user) {
        return user;
    }


    public void programmaticLock(String userId) {
        // 获取锁
        final LockInfo lockInfo = lockTemplate.lock(userId, 30000L, 5000L, RedissonLockExecutor.class);
        if (null == lockInfo) {
            throw new RuntimeException("业务处理中,请稍后再试");
        }
        // 获取锁成功，处理业务
        try {
            System.out.println("执行简单方法1 , 当前线程:" + Thread.currentThread().getName() );
        } finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        //结束
    }

    // 用户在5秒内只能访问1次
    @Lock4j(keys = {"#user.id"}, acquireTimeout = 0, expire = 5000, autoRelease = false)
    public Boolean test(Ur user) {
        return true;
    }




}
